<template>
  <div id="app">
    <!-- 搜索栏 -->
    <div><SearchBar /></div> 
    
    <!-- 轮播图 -->
    <el-carousel :interval="4000" arrow="always">
      <el-carousel-item v-for="(item, index) in bannerList" :key="index">
        <img :src="item.image" alt="推荐商品" class="banner-img">
      </el-carousel-item>
    </el-carousel>
    
    <!-- 商品分类区域 -->
    <div class="category-section">
      <el-button 
        v-for="(category, index) in categoryList" 
        :key="index" 
        type="text" 
        @click="goToCategory(category)"
        class="category-button"
      >
        <img :src="category.image" alt="分类图标" class="category-icon"><br>
        <span>{{ category.name }}</span>
      </el-button>
    </div>
    
    <!-- 限时抢购区域 -->
    <div class="flash-sale-section">
      <h2>限时抢购</h2>
      <div class="flash-sale-grid">
        <!-- 为限时抢购商品添加点击事件  || 'https://picsum.photos/300/300?random='+index -->
        <div 
          class="flash-sale-item" 
          v-for="(item, index) in flashSaleList" 
          :key="index"
          @click="goToProductDetail(item)"
          style="cursor: pointer"
        >
          <img :src="item.img" alt="限时抢购商品" class="flash-sale-img">
          <p>{{ item.name }}</p>
          <p>价格: {{ item.price }}</p>
        </div>
      </div>
    </div>
    
    <!-- 热销商品区域 -->
    <div class="hot-sale-section">
      <div class="section-title">
        <span class="section-title-icon">🔥</span>
        <span>人气新品</span>
      </div>
      <div class="hot-sale-list">
        <!-- 为热销商品添加点击事件 -->
        <div 
          class="hot-sale-item" 
          v-for="(item, index) in hotSaleList" 
          :key="index"
          @click="goToProductDetail(item)"
          style="cursor: pointer"
        >
          <div class="hot-sale-item-container">
            <div class="hot-sale-item-image">
              <img :src="item.img" alt="热销商品">
            </div>
            <div class="hot-sale-item-info">
              <p class="hot-sale-item-name">{{ item.name }}</p>
              <p class="hot-sale-item-price">
                <span class="price-symbol">¥</span>
                <span>{{ item.price }}</span>
              </p>
              <p class="hot-sale-item-sold">已售{{ item.sales }}件</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  <!-- 在模板末尾（</div> 闭合标签前）添加 -->
<div class="cart-button-container">
  <el-button 
    class="cart-btn" 
    @click="goToCart"
    circle
  >
    <el-icon><ShoppingCart /></el-icon>
  </el-button>
</div>
    <!-- 更多推荐区域 -->
    <div class="more-recommend-section" ref="recommendContainer">
      <div class="section-title">
        <span class="section-title-icon">🔥</span>
        <span>更多推荐</span>
      </div>
      <div class="recommend-scroll-container" ref="scrollContainer">
        <div class="recommend-item-grid">
          <!-- 为更多推荐商品添加点击事件 -->
          <div
            v-for="(item, index) in visibleRecommendList"
            :key="index"
            class="recommend-item"
            @click="goToProductDetail(item)"
            style="cursor: pointer"
          >
            <img :src="item.image" alt="推荐商品" class="recommend-item-img">
            <p class="recommend-item-name">{{ item.name }}</p>
            <p class="recommend-item-price">
              <span class="price-symbol">¥</span>
              <span>{{ item.price }}</span>
            </p>
            <p class="recommend-item-sold">已售{{ item.sold }}件</p>
          </div>
        </div>
      </div>
      <div v-if="loading" class="load-more-container">
        <img src="http://localhost:80/loading.png" alt="加载中" class="loading-img">
        <span>加载更多</span>
      </div>
      <div v-if="!hasMore && !loading" class="no-more-container">
        <span>没有更多商品了</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'  // 引入路由钩子
import SearchBar from '../../components/SearchBar/index.vue' 
import { ShoppingCart } from '@element-plus/icons-vue'
import {findHotSales,findKillSales} from '@/api/mall.js'
// 初始化路由
const router = useRouter()

// 模拟数据（为每个商品添加唯一ID）
const bannerList = ref([
  { image: 'https://picsum.photos/1200/400?random=1', name: '推荐商品1' },
  { image: 'https://picsum.photos/1200/400?random=2', name: '推荐商品2' }
])

const categoryList = ref([
  { name: '日用品', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/daily.png' },
  { name: '零食', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/snacks.png' },
  { name: '酒水', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/drink.png' },
  { name: '服饰', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/clothes.png' },
  { name: '数码产品', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/digi.png' },
  { name: '蔬菜水果', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/fruit.png' },
  { name: '全部分类', image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/all.png' }
])

// 限时抢购商品（添加id）
// const flashSaleList = ref([
//   { id: 101, image: '', name: '限时抢购商品1', price: 9.9 },
//   { id: 102, image: '', name: '限时抢购商品2', price: 19.9 },
//   { id: 103, image: '', name: '限时抢购商品3', price: 29.9 },
//   { id: 104, image: '', name: '限时抢购商品4', price: 39.9 }
// ])
// 初始化热销商品
const initHotSaleList = (data) =>{
findHotSales(data).then(res =>{
  console.log("热销商品初始化",res);
  if (res.code === 200) {
    console.log(res)
    hotSaleList.value = res.data
  }else{
    alert("加载失败")
  }
}).catch(err =>{
  console.log("请求失败")
})
}
// 初始化秒杀商品
const initKillSaleList = (data) =>{
findKillSales(data).then(res =>{
  console.log("秒杀商品初始化",res);
  if (res.code === 200) {
    console.log(res)
    flashSaleList.value = res.data
  }else{
    alert("加载失败")
  }
}).catch(err =>{
  console.log("请求失败")
})
}
// 抢购商品
const flashSaleList = ref([
  {
    id: '',
    img: '',
    name: '',
    price: '',
    iskill:'',
   
}])
// 热销商品（添加id）
const hotSaleList = ref([
   {
    id: '',
    img: '',
    name: '',
    price: '',
    sales: ''
  },
])  

// 更多推荐商品（添加id）
const moreRecommendList = ref([
  { id: 301, image: 'https://picsum.photos/300/300?random=61', name: '捆绑打包编织不易断绳子10米', price: 60.00, sold: '1.2万' },
  { id: 302, image: 'https://picsum.photos/300/300?random=62', name: '货车专用加厚防水防晒篷布', price: 30.00, sold: '1.9万' },
  { id: 303, image: 'https://picsum.photos/300/300?random=63', name: '胶合板带锁链木头材质包装箱', price: 80.00, sold: '1.7万' },
  { id: 304, image: 'https://picsum.photos/300/300?random=64', name: '捆绑打包编织不易断绳子10米', price: 50.00, sold: '1.5万' },
  { id: 305, image: 'https://picsum.photos/300/300?random=65', name: '另一个推荐商品1', price: 45.00, sold: '1.3万' },
  { id: 306, image: 'https://picsum.photos/300/300?random=66', name: '另一个推荐商品2', price: 35.00, sold: '1.4万' },
  { id: 307, image: 'https://picsum.photos/300/300?random=67', name: '另一个推荐商品3', price: 55.00, sold: '1.6万' },
  { id: 308, image: 'https://picsum.photos/300/300?random=68', name: '另一个推荐商品4', price: 75.00, sold: '1.1万' },
  { id: 309, image: 'https://picsum.photos/300/300?random=69', name: '另一个推荐商品5', price: 25.00, sold: '1.8万' },
  { id: 310, image: 'https://picsum.photos/300/300?random=70', name: '另一个推荐商品6', price: 65.00, sold: '1.0万' }
])

// 点击事件：跳转到商品购买页面
const goToProductDetail = (product) => {
  // 通过路由跳转，携带商品ID
  router.push({
    name: 'ProductDetail',
    params: { id: product.id }
  })
}

// 其他原有逻辑保持不变
const searchQuery = ref('')
const goToCategory = (category) => {
  console.log(`跳转到${category.name}分类页面`)
}
const goToCart = () => {
  console.log('跳转到购物车页面')
    router.push({ name: 'Cart' }) // 跳转到购物车页面

}

const visibleRecommendList = ref(moreRecommendList.value.slice(0, 6))
const loading = ref(false)
const hasMore = ref(true)
const scrollContainer = ref(null)

const handleScroll = () => {
  if (!scrollContainer.value) return
  console.log('滚动事件触发')
  
  const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value
  if (scrollHeight - scrollTop - clientHeight <= 50) {
    if (!loading.value && hasMore.value) {
      loadMoreRecommend()
    }
  }
}

const loadMoreRecommend = () => {
  console.log('开始加载更多商品')
  loading.value = true
  
  setTimeout(() => {
    const currentLength = visibleRecommendList.value.length
    const newLength = Math.min(currentLength + 2, moreRecommendList.value.length)
    visibleRecommendList.value = moreRecommendList.value.slice(0, newLength)
    
    if (newLength >= moreRecommendList.value.length) {
      hasMore.value = false
    }
    
    loading.value = false
  }, 300)
}

onMounted(() => {
  console.log('组件已挂载')
  initHotSaleList(1);
  initKillSaleList(2);
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #cb3766;
  padding: 0 15px;
  margin-top: 20px;
}
/* 在 style 标签内添加 */
.cart-button-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 100;
}
/* 在原有的<style scoped>标签内添加 */
.cart-btn .el-icon {
  font-size: 24px; /* 图标大小，默认一般是16px，24px放大50% */
}
.cart-btn {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff4d4f; /* 购物车图标颜色 */
  border: none;
}

.cart-btn:hover {
  background-color: #f5f5f5;
}

/* 轮播图样式 */
.banner-img {
  width: 100%;
  height: auto;
  max-height: 300px;
  object-fit: cover;
}

/* 分类区域样式 */
.category-section {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  flex-wrap: wrap;
  padding: 10px 0;
}

.category-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  width: 100px;
}

.category-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 5px;
  border-radius: 50%;
  object-fit: cover;
}

/* 限时抢购区域 */
.flash-sale-section {
  margin: 30px 0;
}

.flash-sale-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.flash-sale-item {
  margin: 10px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.flash-sale-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

/* 热销商品区域 */
.hot-sale-section {
  margin: 30px 0;
}

.hot-sale-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
}

.hot-sale-item {
  margin: 10px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.hot-sale-item-container {
  display: flex;
  align-items: flex-start;
}

.hot-sale-item-image {
  width: 120px;
  height: 120px;
  background-color: #f0f0f0;
  margin-right: 10px;
  flex-shrink: 0;
}

.hot-sale-item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hot-sale-item-info {
  text-align: left;
  flex-grow: 1;
}

.hot-sale-item-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  line-height: 1.4;
}

.hot-sale-item-price {
  color: #ff4d4f;
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: bold;
}

.hot-sale-item-sold {
  color: #999;
  margin: 0;
  font-size: 14px;
}

/* 更多推荐区域 */
.more-recommend-section {
  margin: 30px 0;
  padding-bottom: 80px; /* 为悬浮按钮留出空间 */
}

.recommend-item-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.recommend-item {
  margin: 0;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.recommend-item-img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.recommend-item-name {
  margin: 10px 0 5px 0;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  width: 100%;
  text-align: left;
}

.recommend-item-price {
  color: #ff4d4f;
  margin: 0 0 5px 0;
  font-weight: bold;
  width: 100%;
  text-align: left;
}

.recommend-item-sold {
  color: #999;
  margin: 0;
  font-size: 12px;
  width: 100%;
  text-align: left;
}

/* 加载更多样式 */
.load-more-container {
  margin: 20px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.no-more-container {
  margin: 20px 0;
  color: #999;
  text-align: center;
}

/* 新增：推荐列表滚动容器样式 */
.recommend-scroll-container {
  max-height: 600px; /* 固定高度，确保能滚动 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding-right: 10px; /* 避免滚动条遮挡内容 */
}

/* 修复加载图片样式 */
.loading-img {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>